import time
import hashlib
import requests
import json
from typing import Callable
from functools import lru_cache
import os


# def automaticArchiving(func: Callable):
#     def callable(self):
#         resp: requests.Response = func(self)
#         module_path = os.path.abspath(__file__)
#         module_dir = os.path.dirname(module_path)
#         if not os.path.exists(f"{module_dir}/cx/get_json"):
#             os.makedirs(f"{module_dir}/cx/get_json", mode=os.W_OK)
#         with open(
#             f"{module_dir}/cx/get_json/{func.__name__}.json", "w", encoding="utf-8"
#         ) as f:
#             json.dump(resp.json(), f, ensure_ascii=False)
#         return resp

#     return callable


class CasmartApi(object):
    """喀斯玛官方接口"""

    def __init__(self):
        self.appid = "300045171"
        self.secret = "335a0d4b334dd1f9e05eeda18a508b5c"
        self.format_ = "json"
        self.t = lambda: time.strftime(
            "%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))
        )

    # ^获取商品类型
    # @automaticArchiving
    # @lru_cache(2)
    def get_category_list(self, cid: int | None = "") -> list:
        """
        获取平台分类列表 `GetProductType`

        默认返回所有分类列表

        Args:
            cid (int | None, optional): 分类ID. Defaults to "".

        Returns:
            list: 分类列表
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetProductType"
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{cid}{self.format_}{self.t()}{self.secret}".encode("utf-8")
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        url_s = f"{url}?appid={self.appid}&cIds={cid}&format={self.format_}&t={self.t()}&sign={sign}"
        response = requests.post(url=url_s)
        return response.json()["data"]

    # ^获取商品类型扩展属性
    # @automaticArchiving
    # @lru_cache(2)
    def get_product_type_extend(self, tid: int = 300004006, filter: int = 0):
        """
        获取商品扩展属性 `GetProductTypeExtend`

        默认情况下，返回全部商品扩展属性

        Args:
            tid (int, optional): 商品类型ID,可从get_category_list()获取. Defaults to 300004006.
            filter (int, optional): 属性过滤类型. Defaults to 0. 0: 全部属性 1: 必填属性 2: 非必填属性

        Returns:
            list: 商品扩展属性列表
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetProductTypeExtend"
        # tid/商品类型ID，5：化学试剂（包括危化品）
        md5 = hashlib.md5()
        md5.update(
            a := f"{self.appid}{self.format_}{self.t()}{tid}{self.secret}".encode(
                "utf-8"
            )
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        url_s = f"{url}?appid={self.appid}&format={self.format_}&t={self.t()}&tid={tid}&sign={sign}"
        response = requests.post(url=url_s)
        total = response.json()["data"]
        if filter == 0:
            return total
        elif filter == 1:
            return [i for i in total if i["required"] == 1]
        elif filter == 2:
            return [i for i in total if i["required"] == 0]

    # ^获取品牌
    # @automaticArchiving
    # @lru_cache(2)
    # GetProductBrand
    def get_brand_list(self) -> list:
        """
        获取店铺商品品牌列表信息 `GetProductBrand`

        Returns:
            list: 品牌列表
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetProductBrand"
        # print(self.t())
        # md5
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{self.format_}{self.t()}{self.secret}".encode("utf-8")
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        # print(sign)
        url_s = (
            f"{url}?appid={self.appid}&format={self.format_}&t={self.t()}&sign={sign}"
        )
        # print(url_s)
        response = requests.post(url=url_s)
        return response.json()["data"]

    # ^获取分类
    # @automaticArchiving
    # @lru_cache(2)
    # GetProductCategory
    def get_product_category(self):
        """
        获取商品分类信息树 `GetProductCategory`

        Returns:
            list: 商品分类信息树
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetProductCategory"
        print(self.t())
        # md5
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{self.format_}{self.t()}{self.secret}".encode("utf-8")
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        # print(sign)
        url_s = (
            f"{url}?appid={self.appid}&format={self.format_}&t={self.t()}&sign={sign}"
        )
        print(url_s)
        response = requests.post(url=url_s)
        return response.json()["data"]

    # ^获取分组
    # @lru_cache(2)
    # @automaticArchiving
    def get_product_group(self):
        """获取商品分组信息

        Returns:
            _type_: _description_
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetProductGroup"
        # appid = "300045171"
        # secret = "335a0d4b334dd1f9e05eeda18a508b5c"
        # format_ = "json"
        # t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
        print(self.t())
        # md5
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{self.format_}{self.t()}{self.secret}".encode("utf-8")
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        # print(sign)
        url_s = (
            f"{url}?appid={self.appid}&format={self.format_}&t={self.t()}&sign={sign}"
        )
        print(url_s)
        response = requests.post(url=url_s)
        return response

    def add_product(self, json_data):
        """新增产品信息

        Args:
            json_data (_type_): _description_

        Returns:
            _type_: _description_
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/AddProduct"
        # appid = "300045171"
        # secret = "335a0d4b334dd1f9e05eeda18a508b5c"
        # format_ = "json"
        # t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
        # t = '2023-03-02 15:27:33'
        # con_dict = json_data
        # content = {"data": (None, con_dict)}
        # print(con_dict)
        # print(content)
        # md5
        jsonDataToString = json.dumps(json_data)
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{jsonDataToString}{self.format_}{self.t()}{self.secret}".encode(
                "utf-8"
            )
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        # url_s = f"{url}?={self.appid}&format={self.format_}&t={self.t()}&sign={sign}"
        params = {
            "appid": self.appid,
            "format": self.format_,
            "t": self.t(),
            "sign": sign,
        }
        # print(url_s)
        response = requests.post(
            url=url, params=params, data={"data": jsonDataToString}
        )
        return response

    def update_product(self, json_data):
        """更新产品信息

        Args:
            json_data (_type_): _description_

        Returns:
            _type_: _description_
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/UpdateProduct"
        # t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
        # t = '2023-03-02 15:27:33'
        # 商品数据
        # with open('Product.json', encoding='utf-8') as data_json:
        #     con_dict = json.load(data_json)
        #     content = {'data': (None, json.dumps(con_dict))}
        #     print(content)
        con_dict = json_data
        content = {"data": (None, con_dict)}
        # print(con_dict)
        # print(content)
        # md5
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{con_dict}{self.format_}{self.t()}{self.secret}".encode(
                "utf-8"
            )
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        url_s = (
            f"{url}?appid={self.appid}&format={self.format_}&t={self.t()}&sign={sign}"
        )
        # print(url_s)
        response = requests.post(url=url_s, files=content)
        return response

    def get_orders(self):
        """获取订单列表

        Returns:
            _type_: _description_
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetOrders"
        print(self.t())
        # md5
        params = {
            "appid": self.appid,
            "format": self.format_,
            "starttime": "2023-9-30 17:30:00",
            "endtime": "2024-9-30 17:50:00",
            "t": self.t(),
        }
        md5 = hashlib.md5()
        md5.update(
            a := "{}{}".format("".join(params.values()), self.secret).encode("utf-8")
        )  # 指定需要加密的字符串
        print(a)
        sign = md5.hexdigest()  # 加密后的字符串
        params["sign"] = sign

        response = requests.get(url=url, params=params)
        print(response.url)
        return response

    def get_orders_info(self, ordersn: str):
        """获取订单详情信息

        Args:
            ordersn (str): _description_

        Returns:
            _type_: _description_
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetOrdersInfo"
        print(self.t())
        # md5
        params = {
            "appid": self.appid,
            "format": self.format_,
            "t": self.t(),
            "ordersn": ordersn,
        }
        md5 = hashlib.md5()
        md5.update(
            a := "{}{}".format("".join(params.values()), self.secret).encode("utf-8")
        )  # 指定需要加密的字符串
        print(a)
        sign = md5.hexdigest()  # 加密后的字符串
        params["sign"] = sign
        response = requests.post(url=url, params=params)
        print(response.url)
        return response

    def test_get_category_list(self, cid: int = "") -> list:
        """获取平台分类列表

        不同的分类对应不同的商品扩展属性
        Returns:
            list: 分类列表
        """
        url = "https://api.casmart.com.cn/v2/rest/Supplier/GetProductType"
        print(self.t())
        # md5
        md5 = hashlib.md5()
        md5.update(
            f"{self.appid}{cid}{self.format_}{self.t()}{self.secret}".encode("utf-8")
        )  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串

        url_s = f"{url}?appid={self.appid}&cIds={cid}&format={self.format_}&t={self.t()}&sign={sign}"
        print(url_s)
        response = requests.post(url=url_s)
        return response.json()["data"]
